import { getDbConnection } from '../../utils/db.js';
import bcrypt from 'bcrypt';
import { createError, defineEventHandler, readBody, setCookie } from 'h3';

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { name, username, password } = body;

  // 验证输入
  if (!name || !username || !password) {
    return createError({
      statusCode: 400,
      statusMessage: '请填写所有必填项'
    });
  }

  if (password.length < 6) {
    return createError({
      statusCode: 400,
      statusMessage: '密码长度不能少于6位'
    });
  }

  try {
    const db = await getDbConnection();

    // 开始事务
    await db.run('BEGIN TRANSACTION');

    try {
      // 检查用户名是否已存在
      const existingUser = await db.get('SELECT id FROM users WHERE username = ?', [username]);
      if (existingUser) {
        return createError({
          statusCode: 400,
          statusMessage: '用户名已存在'
        });
      }

      // 加密密码
      const saltRounds = 10;
      const hashedPassword = await bcrypt.hash(password, saltRounds);

      // 创建新用户
      const currentTime = new Date().toISOString();
      const result = await db.run(
        'INSERT INTO users (username, name, password, created_at) VALUES (?, ?, ?, ?)',
        [username, name, hashedPassword, currentTime]
      );

      // 获取新创建的用户信息
      const newUser = await db.get('SELECT id, username, name, created_at FROM users WHERE id = ?', [result.lastID]);
      
      // 提交事务
      await db.run('COMMIT');

    // 创建用户会话（这里简化处理，实际项目中应该使用更安全的会话管理）
    const session = {
      userId: newUser.id,
      username: newUser.username,
      name: newUser.name,
      createdAt: new Date().toISOString()
    };

    // 设置会话cookie（简化版）
    setCookie(event, 'session', JSON.stringify(session), {
      httpOnly: true,
      maxAge: 60 * 60 * 24 * 7, // 7天
      sameSite: 'strict'
    });

    return {
      success: true,
      user: {
        id: newUser.id,
        username: newUser.username,
        name: newUser.name
      }
    };
    } catch (error) {
      // 回滚事务
      await db.run('ROLLBACK');
      throw error;
    }
  } catch (error) {
    console.error('Registration error:', error);
    return createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || '注册失败，请稍后重试'
    });
  }
});
